package com.github.postsanf.yinian.slider.library;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

import com.flaviofaria.kenburnsview.KenBurnsView;
import com.flaviofaria.kenburnsview.RandomTransitionGenerator;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xujiasheng on 16/8/13.
 */
public class MyAdGallery2 extends Gallery implements
        AdapterView.OnItemClickListener,
        AdapterView.OnItemSelectedListener, View.OnTouchListener {
    private Context mContext;
    private int mSwitchTime;
    private Timer mTimer;
    private int curIndex = 0;
    private List<KenBurnsView> listImgs = new ArrayList<KenBurnsView>();
    private List<String> mUris;
    private ImageLoader imageLoader;
    private MyOnItemClickListener mMyOnItemClickListener;

    public MyAdGallery2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyAdGallery2(Context context) {
        super(context);
    }

    public MyAdGallery2(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void start(Context context, List<String> mris,
                      int switchTime) {
        this.mContext = context;
        this.mUris = mris;
        this.mSwitchTime = switchTime;
        imageLoader = ImageLoader.getInstance();
        ininImages();
        setAdapter(new AdAdapter());
        this.setOnItemClickListener(this);
        this.setOnTouchListener(this);
        this.setOnItemSelectedListener(this);
        this.setSoundEffectsEnabled(false);
        this.setAnimationDuration(5000);
        this.setUnselectedAlpha(1);
        setSpacing(0);
        setSelection((getCount() / 2 / listImgs.size()) * listImgs.size());
        setFocusableInTouchMode(true);
        startTimer();
    }

    private void ininImages() {
        for (int i = 0; i < mUris.size(); i++) {
            KenBurnsView imageview = getKenBurnsView();
            imageLoader.displayImage(StringUtils.repaceImgUrl(YNUrlHelper.getCoverUrl2(mContext, mUris.get(i))), imageview);
            listImgs.add(imageview);
        }
    }

    private KenBurnsView getKenBurnsView() {
        KenBurnsView imageview = new KenBurnsView(mContext);
        imageview.setScaleType(ImageView.ScaleType.FIT_XY);
        imageview.setLayoutParams(new Gallery.LayoutParams(
                Gallery.LayoutParams.MATCH_PARENT,
                Gallery.LayoutParams.MATCH_PARENT));
        imageview.setTransitionGenerator(new RandomTransitionGenerator(5000, new LinearInterpolator()));
        return imageview;
    }

    class AdAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (listImgs.size() < 2)
                return listImgs.size();
            return Integer.MAX_VALUE;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return listImgs.get(position % listImgs.size());
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
    }

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
        int kEvent;
        if (isScrollingLeft(e1, e2)) {
            kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
        } else {
            kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
        }
        onKeyDown(kEvent, null);
        return true;

    }

    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
        return e2.getX() > (e1.getX() + 50);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                            float distanceY) {
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (MotionEvent.ACTION_UP == event.getAction()
                || MotionEvent.ACTION_CANCEL == event.getAction()) {
            startTimer();
        } else {
            stopTimer();
        }
        return false;
    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
                               long arg3) {
        curIndex = position % listImgs.size();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                            long arg3) {
        if (mMyOnItemClickListener != null) {
            mMyOnItemClickListener.onItemClick(curIndex);
        }
    }

    public void setMyOnItemClickListener(MyOnItemClickListener listener) {
        mMyOnItemClickListener = listener;
    }

    public interface MyOnItemClickListener {
        void onItemClick(int curIndex);
    }

    public void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public void startTimer() {
        if (mTimer == null && listImgs.size() > 1 && mSwitchTime > 0) {
            mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                public void run() {
                    handler.sendMessage(handler.obtainMessage(1));
                }
            }, mSwitchTime, mSwitchTime);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            onScroll(null, null, 1, 0);
            onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
        }
    };
}

